<template>
  <jc-bar prve-btn @prve="$router.back()" :extensionBtn="true">
    <template #default>
      <div style="padding: 5px; width: 100%; padding-top: 30px">
        <v-text-field
          v-if="sliderIndex === 0 || sliderIndex === 1"
          autofocus
          label="请输入序号/标题/歌词"
          v-model="seacherStr"
          @input="onInput"
        ></v-text-field>
        <!-- :model-value="jwSearchStr"
        @update:model-value="handleChangeSelectJwValue" -->
        <JwAutocomplete
          v-if="sliderIndex === 2"
          v-model:bibleSearchList="bibleSearchList"
          :audtocompleted="false"
          @onLoading="onLoading"
          v-model="seacherStr"
        />
      </div>
    </template>
    <template #barextension>
      <div class="w-full">
        <v-tabs
          color="primary"
          @update:model-value="onChange"
          align-tabs="center"
          :model-value="tab"
          class="text-title"
        >
          <v-tab :value="SEARCH_TAB_ENUM.title">按标题序号 {{ searchTitleLength }}</v-tab>
          <v-tab :value="SEARCH_TAB_ENUM.lyric">按歌词 {{ searchLyricLength }}</v-tab>
          <v-tab :value="SEARCH_TAB_ENUM.jinwen">搜经文 {{ searchJinwenLength }}</v-tab>
        </v-tabs>
      </div>
    </template>
  </jc-bar>

  <STabsWindow class="w-full h-full" v-model="sliderIndex" @slide-change="handleSliderChange">
    <SwiperSlide class="h-full">
      <v-virtual-scroll
        :style="{ height: '100%' }"
        :items="searchList"
        v-if="searchList.length > 0 && sliderIndex == 0 && seacherStr"
      >
        <template v-slot:default="{ item }">
          <JcListItem :show-type="true" :key="item._id" :item="item" @itemclick="() => handleClickItem(item, index)" />
        </template>
      </v-virtual-scroll>
      <Empty icon="Search" v-if="!seacherStr && !isShowTitleEmtpy">
        <div class="text-subtitle text-sm text-center">请输入要搜索的关键词</div>
      </Empty>
      <Empty v-if="isShowTitleEmtpy">
        <div class="text-subtitle text-sm text-center">没有找到相关数据</div>
      </Empty>
    </SwiperSlide>
    <SwiperSlide class="h-full">
      <v-virtual-scroll
        :style="{ height: '100%' }"
        :items="lyricSearchList"
        v-if="lyricSearchList.length > 0 && sliderIndex == 1 && seacherStr"
      >
        <template v-slot:default="{ item, index }">
          <JcListItem
            :show-type="true"
            :key="item._id"
            :item="item"
            @itemclick="() => handleClickItem(item, index)"
            height="auto"
          >
            <template v-slot:lyric>
              <div class="text-caption" v-html="parseLyric(item.dmtUrl.lyric)"></div>
            </template>
          </JcListItem>
        </template>
      </v-virtual-scroll>

      <Empty icon="Search" v-if="!seacherStr && !isShowLyricEmtpy">
        <div class="text-subtitle text-sm text-center">请输入要搜索的关键词</div>
      </Empty>
      <Empty v-if="isShowLyricEmtpy">
        <div class="text-subtitle text-sm text-center">没有找到相关数据</div>
      </Empty>
    </SwiperSlide>
    <SwiperSlide class="100%">
      <template v-if="tranBibleSearchList.length > 0 && !loading && seacherStr">
        <v-virtual-scroll
          :style="{ height: '100%' }"
          :items="tranBibleSearchList"
          v-if="tranBibleSearchList.length > 0 && sliderIndex == 2 && seacherStr"
        >
          <template v-slot:default="{ item, index }">
            <v-list-item @click="handleChangeSelectJwValue(item.title)">
              <v-list-item-title>
                <span class="text-title">
                  {{ item.title }}
                </span>
              </v-list-item-title>
              <v-list-item-subtitle>
                <div class=" " v-html="item.subtitle"></div>
              </v-list-item-subtitle>
            </v-list-item>
          </template>
        </v-virtual-scroll>
      </template>
      <template v-else-if="loading">
        <div class="h-full w-full overflow-hidden text-title flex justify-center align-center flex-col">
          <div class="text-xl">加载中...</div>
        </div>
      </template>
      <template v-else-if="!loading && seacherStr">
        <Empty icon="Search">
          <div class="text-subtitle text-sm text-center">
            没有查询到相关数据
            <div class="text-xl">支持输入关键字模糊查询</div>
            <div class="text-xl">支持输入章节输入查询</div>
            <div class="text-xl">例：徒1:1 或 徒2：1-3</div>
          </div>
        </Empty>
      </template>
      <template v-else>
        <Empty icon="Search">
          <div class="text-subtitle">支持输入关键字模糊查询</div>
          <div class="text-subtitle">支持输入章节输入查询</div>
          <div class="text-subtitle">例：徒1:1 或 徒2：1-3</div>
        </Empty>

        <!-- <JingWen @select="handleJingWenSelect"></JingWen> -->
      </template>
    </SwiperSlide>
  </STabsWindow>

  <div class="text-orange-300 hidden"></div>
</template>

<script>
import { mapState } from "vuex";
import JcBar from "@/layout/JcBar";
import { gedanController } from "@/api/cloudbase-user-action-log";
import STabsWindow from "@/components/STabsWindow.vue";
import { SwiperSlide } from "swiper/vue";
import JingWen from "./JingWen.vue";
import { PLAYNEWPAGENAME, PLAY_PAGE_TYPE_ENUM } from "@/utils/constant";
import StarList from "../Sgb/StarList.vue";
import JcListItem from "@/components/JcListItem.vue";
import JwAutocomplete from "@/views/TouYing/new/components/Autocomplete/JwAutocomplete.vue";
import Empty from "@/jcui/JcEmty/emty.vue";
import { GEDAN_LIST_TYPE } from "@/utils/constant";
import { getShiJiItemByLyric, tranData } from "@/api/cloudbase-sgbedit";
import { identity } from "@vueuse/core/index.cjs";
const SEARCH_TAB_ENUM = {
  title: "title",
  lyric: "lyric",
  jinwen: "jinwen",
};
export default {
  name: "seacherSgb",
  components: {
    JcBar,
    JingWen,
    STabsWindow,
    SwiperSlide,
    StarList,
    JcListItem,
    JwAutocomplete,
    Empty,
  },
  data() {
    return {
      seacherStr: "",
      list: [],
      page: 1,
      limit: 20,
      total: 0,
      typelist: [],
      selectItemIndex: 0,
      tab: SEARCH_TAB_ENUM.title,
      searchList: [],
      lyricSearchList: [],
      SEARCH_TAB_ENUM,
      jwSearchStr: null,
      bibleSearchList: [],
      loading: false,
    };
  },

  computed: {
    zanmeiTYpe() {
      return (typeId) => {
        let result = "";
        if (this.typelist.length > 0) {
          result = this.typelist.filter((i) => i.id === typeId)[0].name;
        }
        return result;
      };
    },
    parseLyric() {
      return (lyric) => {
        if (!lyric) return null;
        return lyric;
      };
    },
    ...mapState("audio", ["paused"]),
    sliderIndex: {
      set(val) {
        switch (val) {
          case 0:
            this.tab = SEARCH_TAB_ENUM.title;
            break;
          case 1:
            this.tab = SEARCH_TAB_ENUM.lyric;
            break;
          case 2:
            this.tab = SEARCH_TAB_ENUM.jinwen;
            break;
        }
      },

      get() {
        switch (this.tab) {
          case SEARCH_TAB_ENUM.title:
            return 0;
          case SEARCH_TAB_ENUM.lyric:
            return 1;
          case SEARCH_TAB_ENUM.jinwen:
            return 2;
        }
        return 0;
      },
    },
    searchTitleLength() {
      const length = this.searchList.length;

      if (length && this.seacherStr) {
        return `${length}条`;
      }
      return "";
    },
    searchLyricLength() {
      const length = this.lyricSearchList.length;
      if (length && this.seacherStr) {
        return `${length}条`;
      }
      return "";
    },
    searchJinwenLength() {
      const length = this.bibleSearchList.length;
      if (length && this.seacherStr) {
        return `${length}条`;
      }
      return "";
    },
    isShowTitleEmtpy() {
      return this.seacherStr && this.searchList.length === 0;
    },
    isShowLyricEmtpy() {
      return this.seacherStr && this.searchLyricLength.length === 0;
    },
    tranBibleSearchList() {
      return this.bibleSearchList.map((item) => {
        return {
          title: item.value,
          subtitle: item.title,
        };
      });
    },
  },
  mounted() {
    // this.onInput();
  },
  methods: {
    init() {
      return new Promise((resolve) => {
        this.$store.dispatch("sgb/getAllLIst").then((res) => {
          this.list = res;
          this.total = res.length;
          this.$store.dispatch("sgb/getAllShiJiList").then((type) => {
            this.typelist = type;
            resolve();
          });
        });
      });
    },
    onChange(e) {
      this.tab = e;
      // this.onInput();
    },
    onInput() {
      this.handleGetList().then(({ searchList, lyricSearchList }) => {
        this.searchList = searchList;
        this.lyricSearchList = lyricSearchList;
      });
    },
    handleGetList() {
      return new Promise(async (resolve) => {
        const res = async () => {
          const searchList = this.list.filter((item) => {
            const title = item.xuhao.toString().padStart(3, "0") + item.mulu;
            if (this.seacherStr.trim() !== "") {
              return title.indexOf(this.seacherStr) !== -1;
            }

            return true;
          });
          let lyricSearchList = [];
          try {
            const res = await getShiJiItemByLyric(this.seacherStr);
            lyricSearchList = res.map((item, index) => ({ ...tranData(item), dmtUrl: res[index].dmturl, isad: true }));
          } catch (error) {
            console.log("searcy error:", error);
          }

          return {
            searchList,
            lyricSearchList,
          };
        };

        if (this.list.length < 1) {
          this.init().then(async () => {
            resolve(await res());
          });
        } else {
          resolve(await res());
        }
      });
    },

    handleClickItem(item) {
      const gedanId = this.$route.query.gedanid;
      // 有歌单ID的话就从是添加歌单的功能
      if (gedanId) {
        this.addGeDan(item._id);
      } else {
        // 没有的话就直接跳转到播放页面
        this.$router.push({
          name: PLAYNEWPAGENAME,
          params: {
            id: item._id,
            gedanid: item.shijiIndex,
            type: PLAY_PAGE_TYPE_ENUM.TYPE_SHIJI,
          },
          query: {
            from: this.$route.fullPath,
          },
        });
      }
    },
    handleTabsChange() {
      this.handleGetList();
    },
    handleJingWenSelect(query) {
      const gedanId = this.$route.query.gedanid;
      console.log(query);

      // 有歌单ID的话就从是添加歌单的功能
      if (gedanId) {
        const id = query.shortTitle + query.zhang + ":" + (query.currentIndex + 1);
        this.addGeDan(id + "|" + GEDAN_LIST_TYPE.jw);
        return;
      } else {
        this.$router.push({
          name: "JingWengRes",
          query,
        });
      }
    },
    handleChangeSelectJwValue(value) {
      const gedanId = this.$route.query.gedanid;
      // 有歌单ID的话就从是添加歌单的功能
      if (gedanId) {
        this.addGeDan(value + "|" + GEDAN_LIST_TYPE.jw);
        return;
      } else {
        this.$router.push({
          name: "JingWengRes",
          query: { id: value },
        });
      }
    },
    addGeDan(id) {
      const gedanId = this.$route.query.gedanid;
      gedanController
        .addGeDanDatailList(gedanId, id)
        .then(() => {
          this.$toast.success("添加成功");
        })
        .catch((err) => {
          this.$jcmsg({ msg: err, type: "error" }).show();
        });
    },
    onLoading(val) {
      console.log("loading-->", val);
      this.loading = val;
    },
    handleSliderChange(index) {
      console.log("index-->", index);
      if (this.seacherStr && index === 2) {
        // this.handleGetBibleList();
      }
    },
  },
};
</script>
